$(function () {
    var aid = "8412";
    var key = "8412";
    //门锁设定
    var edge;
    var switch_flag = 0;
    var states_flag = 0;
    var myDoorMac = "00:12:4B:00:1A:BE:4F:A3"; // 传感器的MAC地址
    var door = new WSNRTConnect(aid, key); // 创建数据连接服务对象
    door.setServerAddr("192.168.12.110:28080"); // 服务器地址
    door.connect();
    //门锁初始化
    door.onConnect = function () { // 连接成功回调函数
        door.sendMessage(myDoorMac, "{A0=?,A1=?}"); // 向传感器发送数据
        $("#DoorConnectState").text("门锁服务连接成功！");
    };
    door.onConnectLost = function () { // 数据服务掉线回调函数
        $("#DoorConnectState").text("门锁服务掉线！");
    };

    
    // 智能门锁回调函数
    door.onmessageArrive = function (mac, dat) {
        if (mac == myDoorMac) { // 判断传感器Mac地址
            if (dat[0] == '{' && dat[dat.length - 1] == '}') { // 判断字符串首尾是否为{}
                dat = dat.substr(1, dat.length - 2); // 截取{}内的字符串
                var its = dat.split(','); // 以‘,’来分割字符串
                for (var x in its) {
                    var t = its[x].split('='); // 以‘=’来分割字符串
                    if (t.length != 2) continue;
                    if (t[0] == "D1") { // 判断参数D1
                        edge = parseInt(t[1]); // 将字符串转换为整数
                        if (edge == 1) {
                            $("#door_states").text("门锁开启");
                            $("#door_switch").text("关闭");
                            switch_flag = 0;
                            if (states_flag == 1) {
                                alert("电磁锁打开");
                                states_flag = 0;
                            }
                        } else {
                            $("#door_states").text("门锁关闭");
                            $("#door_switch").text("开门");
                            switch_flag = 1;
                            if (states_flag == 1) {
                                alert("电磁锁关闭");
                                states_flag = 0;
                            }
                        }
                    }
                }
            }
        }
    };
    // 门锁开关检测
    $("#door_states_search").click(function () {
        door.sendMessage(myDoorMac, "{D1=?}"); // 发送查询指令
        states_flag = 1;
    });
    // 手动开关门操作
    $("#door_switch").click(function () { // 电磁阀开关
        if (switch_flag) {
            door.sendMessage(myDoorMac, "{OD1=1,D1=?}"); // 电磁阀指令
        } else {
            door.sendMessage(myDoorMac, "{CD1=1,D1=?}"); // 电磁阀指令
        }
    });
});